package com.xbongbong.process.ding;

import com.alibaba.dingtalk.openapi.helper.AuthHelper;
import com.alibaba.dingtalk.openapi.helper.DingtalkWorkrecordHelper;
import com.alibaba.dingtalk.openapi.helper.Env;
import com.alibaba.dingtalk.openapi.vo.workrecord.CancelTask;
import com.alibaba.dingtalk.openapi.vo.workrecord.CancelTaskRequest;
import com.alibaba.dingtalk.openapi.vo.workrecord.DeleteProcess;
import com.alibaba.dingtalk.openapi.vo.workrecord.DeleteProcessInstance;
import com.alibaba.dingtalk.openapi.vo.workrecord.DeleteProcessInstanceRequest;
import com.alibaba.dingtalk.openapi.vo.workrecord.DeleteProcessRequest;
import com.alibaba.dingtalk.openapi.vo.workrecord.FormComponentValueVo;
import com.alibaba.dingtalk.openapi.vo.workrecord.SaveFakeProcessInstance;
import com.alibaba.dingtalk.openapi.vo.workrecord.SaveFakeProcessInstanceRequest;
import com.alibaba.dingtalk.openapi.vo.workrecord.SaveTask;
import com.alibaba.dingtalk.openapi.vo.workrecord.SaveTaskRequest;
import com.alibaba.dingtalk.openapi.vo.workrecord.TaskTopVo;
import com.alibaba.dingtalk.openapi.vo.workrecord.UpdateProcessInstance;
import com.alibaba.dingtalk.openapi.vo.workrecord.UpdateProcessInstanceRequest;
import com.alibaba.dingtalk.openapi.vo.workrecord.UpdateTask;
import com.alibaba.dingtalk.openapi.vo.workrecord.UpdateTaskRequest;
import com.alibaba.fastjson.JSON;
import com.xbongbong.paas.constant.PaasConstant;
import com.xbongbong.paas.domain.entity.PaasProcessNodeTaskEntity;
import com.xbongbong.paas.domain.entity.PaasProcessTaskEntity;
import com.xbongbong.paas.elasticsearch.util.XbbElasticsearchRestTemplate;
import com.xbongbong.paas.enums.IndexTypeEnum;
import com.xbongbong.paas.model.PaasProcessNodeTaskModel;
import com.xbongbong.paas.model.PaasProcessTaskModel;
import com.xbongbong.paas.pojo.dto.PaasFormDataEsInitDTO;
import com.xbongbong.paas.pojo.vo.PaasFormDataEsInitVO;
import com.xbongbong.paas.toolbox.exception.XbbException;
import com.xbongbong.paas.toolbox.util.DateUtil;
import com.xbongbong.pro.companyconfig.pojo.CompanyConfigWorkrecordValuePojo;
import com.xbongbong.pro.config.ProBaseConfig;
import com.xbongbong.pro.enums.errorcodes.BiErrorCodeEnum;
import com.xbongbong.pro.enums.workrecord.enums.WorkrecordResultEnum;
import com.xbongbong.pro.enums.workrecord.enums.WorkrecordStatusEnum;
import com.xbongbong.pro.enums.workrecord.enums.WorkrecordTemplateEnum;
import com.xbongbong.pro.message.pojo.PushRefTypePojo;
import com.xbongbong.pro.process.pojo.dto.WorkrecordInstanceDTO;
import com.xbongbong.pro.process.pojo.dto.WorkrecordTaskDTO;
import com.xbongbong.pro.process.pojo.dto.WorkrecordTaskOption;
import com.xbongbong.pro.process.pojo.dto.WorkrecordUpdateTaskDTO;
import com.xbongbong.saas.enums.CompanyConfigEnum;
import com.xbongbong.saas.enums.DingtalkPageUrlEnum;
import com.xbongbong.sys.domain.entity.CompanyConfigEntity;
import com.xbongbong.sys.model.CompanyConfigModel;
import org.apache.http.HttpEntity;
import org.apache.http.entity.ContentType;
import org.apache.http.nio.entity.NStringEntity;
import org.elasticsearch.client.Request;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Objects;

/**
 * 钉钉待办处理
 * @author xingxing.xiao
 * @date 2019/08/02 20:05
 */
@Service("dingtalkWorkrecordService")
@Deprecated
public class DingtalkWorkrecordServiceImpl implements DingtalkWorkrecordService {

    private static final Logger LOG = LoggerFactory.getLogger(DingtalkWorkrecordServiceImpl.class);

    @Resource
    private AuthHelper authHelper;
    @Resource
    private ProBaseConfig proBaseConfig;
    @Resource
    private CompanyConfigModel companyConfigModel;
    @Resource
    private PaasProcessNodeTaskModel paasProcessNodeTaskModel;
    @Resource
    private PaasProcessTaskModel paasProcessTaskModel;
    @Resource
    private XbbElasticsearchRestTemplate xbbElasticsearchRestTemplate;

    /**
     * 获取待办配置
     * @param corpid
     * @return 开启待办，返回processCode; 不开启待办返回null
     * @throws
     * @author xingxing.xiao
     * @date 2019/08/03 16:57
     */
    @Override
    public String getCompanyWorkrecordProcessCode(String corpid){
        CompanyConfigEntity companyConfigEntity;
        String dingtalkWorkrecordAlias = CompanyConfigEnum.DINGTALK_WORKRECORD.getAlias();
        companyConfigEntity = companyConfigModel.getByConfigAlias(dingtalkWorkrecordAlias, corpid);
        if (companyConfigEntity == null) {
            // 配置表没有记录，表示没开启
            return null;
        }

        String configValue = companyConfigEntity.getConfigValue();
        CompanyConfigWorkrecordValuePojo configValuePojo = JSON.parseObject(configValue, CompanyConfigWorkrecordValuePojo.class);

        // 若开启钉钉待办同步，查询processCode
        if (Objects.equals(configValuePojo.getEnable(), 1)) {
            String dingtalkProcessCode = configValuePojo.getDingtalkProcessCode();
            return dingtalkProcessCode;
        }

        // 其余情况也返回null
        return null;
    }

    /**
     * 创建钉钉待办实例
     * @author xingxing.xiao
     * @date 2019/08/03 14:46
     */
    @Override
    public void createWorkrecordInstance(WorkrecordInstanceDTO workrecordInstanceDTO) {
        LOG.warn("创建钉钉待办实例,开始拼装请求,公司id:"+workrecordInstanceDTO.getCorpid());
        String corpid = workrecordInstanceDTO.getCorpid();

        String accessToken;
        String agentId;
        try {
            accessToken = authHelper.getAccessToken(corpid);
            agentId = authHelper.getAgentId(corpid, Env.DING_XBB_APP_ID);
        } catch (Exception e) {
            LOG.error("获取accessToken或agentId失败", e);
            return ;
        }

        String userid = workrecordInstanceDTO.getUserId();
        String userName = workrecordInstanceDTO.getUserName();
        String formName = workrecordInstanceDTO.getFormName();
        String summaryTitle = workrecordInstanceDTO.getSummaryTitle();
        Integer submitTime = workrecordInstanceDTO.getSubmitTime();
        String processCode = workrecordInstanceDTO.getDingtalkProcessCode();
        Long processTaskId = workrecordInstanceDTO.getOptions().getProcessTaskId();
        // 处理跳转链接
        String linkUrl = formatDingtalkLinkUrl(corpid, workrecordInstanceDTO.getOptions());

        SaveFakeProcessInstance instance = new SaveFakeProcessInstance();
        SaveFakeProcessInstanceRequest request = new SaveFakeProcessInstanceRequest();
        request.setTitle(formName);
        request.setAgentid(Long.valueOf(agentId));
        request.setProcess_code(processCode);
        request.setOriginator_user_id(userid);
        request.setUrl(linkUrl);
        List<FormComponentValueVo> formComponentValueVoList = new ArrayList<>();
        // 组件-内容提要
        FormComponentValueVo summaryComponetVo = new FormComponentValueVo();
        summaryComponetVo.setName(WorkrecordTemplateEnum.SUMMARY.getName());
        summaryComponetVo.setValue(summaryTitle);
        formComponentValueVoList.add(summaryComponetVo);
        // 组件-提交人
        FormComponentValueVo userNameComponetVo = new FormComponentValueVo();
        userNameComponetVo.setName(WorkrecordTemplateEnum.USER_NAME.getName());
        userNameComponetVo.setValue(userName);
        formComponentValueVoList.add(userNameComponetVo);
        // 组件-提交时间
        FormComponentValueVo submitTimeComponetVo = new FormComponentValueVo();
        submitTimeComponetVo.setName(WorkrecordTemplateEnum.SUBMITTIME.getName());
        String timeValue = DateUtil.getString(submitTime, new SimpleDateFormat("yyyy-MM-dd HH:mm"));
        submitTimeComponetVo.setValue(timeValue);
        formComponentValueVoList.add(submitTimeComponetVo);
        request.setForm_component_values(formComponentValueVoList);
        instance.setRequest(request);
        LOG.warn("创建钉钉待办实例,结束拼装请求,公司id:"+workrecordInstanceDTO.getCorpid());
        try {
            DingtalkWorkrecordHelper.ProcessInstanceResponse processInstanceResponse = DingtalkWorkrecordHelper.createWorkrecordInstance(instance, accessToken);
            LOG.warn("创建钉钉待办实例,结束接口调用,公司id:"+workrecordInstanceDTO.getCorpid());
            if (Objects.nonNull(processInstanceResponse) && Objects.equals(processInstanceResponse.getErrcode(), 0L)) {
                String processInstanceId = processInstanceResponse.getResult().getProcess_instance_id();
                // 更新表
                PaasProcessTaskEntity paasProcessTaskEntity = new PaasProcessTaskEntity();
                paasProcessTaskEntity.setId(processTaskId);
                paasProcessTaskEntity.setCorpid(corpid);
                paasProcessTaskEntity.setDingtalkProcessInstanceId(processInstanceId);
                paasProcessTaskModel.update(paasProcessTaskEntity);
            }
        } catch (Exception e) {
            LOG.error("DingtalkWorkrecordMessageImpl.createWorkrecordInstance 访问创建钉钉待办实例 失败：", e);
        }
    }

    /**
     * 更新钉钉待办实例
     * @param corpid
     * @param processInstanceId
     * @param workrecordResultEnum
     * @return
     */
    @Override
    public boolean updateWorkrecordInstance(String corpid, String processInstanceId, WorkrecordResultEnum workrecordResultEnum) {
        LOG.warn("更新钉钉待办实例,开始拼装请求,公司id:"+corpid);
        String accessToken;
        String agentId;
        try {
            accessToken = authHelper.getAccessToken(corpid);
            agentId = authHelper.getAgentId(corpid, Env.DING_XBB_APP_ID);
        } catch (Exception e) {
            LOG.error("获取accessToken或agentId失败", e);
            return false;
        }

        UpdateProcessInstance updateProcessInstance = new UpdateProcessInstance();
        UpdateProcessInstanceRequest request = new UpdateProcessInstanceRequest();
        request.setAgentid(Long.valueOf(agentId));
        request.setProcess_instance_id(processInstanceId);
        switch (workrecordResultEnum) {
            case AGREE:
                request.setStatus(WorkrecordStatusEnum.COMPLETED.getAlias());
                request.setResult(WorkrecordResultEnum.AGREE.getAlias());
                break;
            case REFUSE:
                request.setStatus(WorkrecordStatusEnum.COMPLETED.getAlias());
                request.setResult(WorkrecordResultEnum.REFUSE.getAlias());
                break;
            case TERMINATED:
                request.setStatus(WorkrecordStatusEnum.TERMINATED.getAlias());
                // 本来不应该加result，但钉钉接口有问题
                request.setResult(WorkrecordResultEnum.AGREE.getAlias());
                break;
            default:
                break;
        }
        updateProcessInstance.setRequest(request);
        LOG.warn("更新钉钉待办实例,结束拼装请求,公司id:"+corpid);
        try {
            DingtalkWorkrecordHelper.BaseResponse baseResponse = DingtalkWorkrecordHelper.updateWorkrecordInstance(updateProcessInstance, accessToken);
            if (Objects.equals(baseResponse.getErrcode(), 0L)) {
                return true;
            }
            LOG.warn("更新钉钉待办实例,返回拼装请求,公司id:"+corpid+ ">>" + JSON.toJSONString(baseResponse));
        } catch (Exception e) {
            LOG.error("DingtalkWorkrecordMessageImpl.updateWorkrecordInstance 更新钉钉待办实例 失败：", e);
        }
        return false;
    }

    /**
     * 删除钉钉待办实例
     * @param corpid
     * @param processInstanceId
     * @return
     * @throws
     * @author xingxing.xiao
     * @date 2019/09/12 16:39
     */
    @Override
    public boolean deleteWorkrecordInstance(String corpid, String processInstanceId) {
        String accessToken;
        String agentId;
        try {
            accessToken = authHelper.getAccessToken(corpid);
            agentId = authHelper.getAgentId(corpid, Env.DING_XBB_APP_ID);
        } catch (Exception e) {
            LOG.error("获取accessToken或agentId失败", e);
            return false;
        }

        DeleteProcessInstance instance = new DeleteProcessInstance();
        DeleteProcessInstanceRequest request = new DeleteProcessInstanceRequest();
        request.setAgentid(Long.valueOf(agentId));
        request.setProcess_instance_id(processInstanceId);
        instance.setRequest(request);
        try {
            DingtalkWorkrecordHelper.BaseResponse baseResponse = DingtalkWorkrecordHelper.deleteWorkrecordInstance(instance, accessToken);
            if (Objects.equals(baseResponse.getErrcode(), 0L)) {
                return true;
            }
        } catch (Exception e) {
            LOG.error("DingtalkWorkrecordMessageImpl.deleteWorkrecordInstance 删除钉钉待办实例 失败：", e);
        }
        return false;
    }

    /**
     * 创建流程任务
     * @param workrecordTaskDTO
     * @return
     * @throws
     * @author xingxing.xiao
     * @date 2019/08/05 11:31
     */
    @Override
    public void createWorkrecordTask(WorkrecordTaskDTO workrecordTaskDTO) {
        LOG.warn("创建钉钉待办任务,开始拼装请求,公司id:"+workrecordTaskDTO.getCorpid());
        String corpid = workrecordTaskDTO.getCorpid();
        String accessToken;
        String agentId;
        try {
            accessToken = authHelper.getAccessToken(corpid);
            agentId = authHelper.getAgentId(corpid, Env.DING_XBB_APP_ID);
        } catch (Exception e) {
            LOG.error("获取accessToken或agentId失败", e);
            return ;
        }

        String processInstanceId = workrecordTaskDTO.getDingtalkProcessInstanceId();
        List<WorkrecordTaskOption> taskOptions = workrecordTaskDTO.getTaskOptions();

        SaveTask taskEntity = new SaveTask();
        SaveTaskRequest request = new SaveTaskRequest();
        request.setAgentid(Long.valueOf(agentId));
        request.setProcess_instance_id(processInstanceId);
        // 流程节点id 就取 "TASK-" + 第一个nodeTaskId
        String activityId = "TASK-" + taskOptions.get(0).getOptions().getProcessNodeTaskId();
        request.setActivity_id(activityId);
        // 建立 userid 和 processNodeTaskId 的对应关系
        Map<String, Object> userTaskMap = new HashMap<>(PaasConstant.DEFAULT_INITIAL_CAPACITY);
        List<TaskTopVo> tasks = new ArrayList<>();
        for (WorkrecordTaskOption taskOption : taskOptions) {
            TaskTopVo task = new TaskTopVo();
            String userId = taskOption.getUserId();
            task.setUserid(userId);
            // 处理跳转链接
            String linkUrl = formatDingtalkLinkUrl(corpid, taskOption.getOptions());
            task.setUrl(linkUrl);
            tasks.add(task);

            // 因为每个流程节点的审批人是唯一的，所以 userId 可以作为 key
            userTaskMap.put(userId, taskOption.getOptions().getProcessNodeTaskId());
        }
        request.setTasks(tasks);
        taskEntity.setRequest(request);
        try {
            LOG.warn("创建钉钉待办任务,结束拼装请求,公司id:"+workrecordTaskDTO.getCorpid());
            DingtalkWorkrecordHelper.TaskResponse taskResponse = DingtalkWorkrecordHelper.createWorkrecordTask(taskEntity, accessToken);
            if (Objects.nonNull(taskResponse) && Objects.equals(taskResponse.getErrcode(), 0L)) {
                List<PaasProcessNodeTaskEntity> nodeTaskList = new ArrayList<>();

                List<DingtalkWorkrecordHelper.TaskResponse.Task> taskList = taskResponse.getTasks();
                for (DingtalkWorkrecordHelper.TaskResponse.Task task : taskList) {

                    // 根据返回值找出对应关系
                    Long dingtalkTaskId = task.getTask_id();
                    String userid = task.getUserid();

                    PaasProcessNodeTaskEntity nodeTaskEntity = new PaasProcessNodeTaskEntity();
                    // 主键: 从 userTaskMap 中找对应关系
                    String nodeTaskId = userTaskMap.get(userid).toString();
                    if (Objects.isNull(nodeTaskId) || nodeTaskId.isEmpty()) {
                        continue;
                    }
                    nodeTaskEntity.setId(Long.valueOf(nodeTaskId));
                    // 同一个流程节点下的所有任务的流程节点id都一样
                    nodeTaskEntity.setDingtalkWorkrecordActivityId(activityId);
                    nodeTaskEntity.setDingtalkWorkrecordTaskId(dingtalkTaskId.toString());
                    // 冗余 钉钉待办实例id
                    nodeTaskEntity.setDingtalkProcessInstanceId(processInstanceId);
                    nodeTaskList.add(nodeTaskEntity);
                }
                // 批量更新
                paasProcessNodeTaskModel.updateBatch(nodeTaskList, corpid);
            }
        } catch (Exception e) {
            LOG.error("DingtalkWorkrecordMessageImpl.createWorkrecordTask 撤销钉钉待办实例 失败：", e);
        }
    }

    /**
     * 更新单个任务
     * @param workrecordUpdateTaskDTO
     * @param workrecordResultEnum
     * @return
     * @throws
     * @author xingxing.xiao
     * @date 2019/08/05 08:41
     */
    @Override
    public boolean updateSingleWorkrecordTask(WorkrecordUpdateTaskDTO workrecordUpdateTaskDTO, WorkrecordResultEnum workrecordResultEnum) {
        LOG.warn("更新钉钉待办任务,开始拼装请求,公司id:"+workrecordUpdateTaskDTO.getCorpid());
        String corpid = workrecordUpdateTaskDTO.getCorpid();
        String accessToken;
        String agentId;
        try {
            accessToken = authHelper.getAccessToken(corpid);
            agentId = authHelper.getAgentId(corpid, Env.DING_XBB_APP_ID);
        } catch (Exception e) {
            LOG.error("获取accessToken或agentId失败", e);
            return false;
        }

        String dingtalkWorkrecordTaskId = workrecordUpdateTaskDTO.getDingtalkTaskId();
        if (Objects.isNull(dingtalkWorkrecordTaskId) || dingtalkWorkrecordTaskId.isEmpty()) {
            return false;
        }
        String dingtalkProcessInstanceId = workrecordUpdateTaskDTO.getDingtalkInstanceId();

        UpdateTask updateTask = new UpdateTask();
        UpdateTaskRequest request = new UpdateTaskRequest();
        request.setAgentid(Long.valueOf(agentId));
        request.setProcess_instance_id(dingtalkProcessInstanceId);
        List<TaskTopVo> tasks = new ArrayList<>();
        TaskTopVo task = new TaskTopVo();
        task.setTask_id(Long.valueOf(dingtalkWorkrecordTaskId));
        switch (workrecordResultEnum) {
            case AGREE:
                task.setStatus(WorkrecordStatusEnum.COMPLETED.getAlias());
                task.setResult(WorkrecordResultEnum.AGREE.getAlias());
                break;
            case REFUSE:
                task.setStatus(WorkrecordStatusEnum.COMPLETED.getAlias());
                task.setResult(WorkrecordResultEnum.REFUSE.getAlias());
                break;
            case CANCELED:
                task.setStatus(WorkrecordStatusEnum.CANCELED.getAlias());
                // 本来不应该加result，但钉钉接口有问题
                task.setResult(WorkrecordResultEnum.AGREE.getAlias());
                break;
            default:
                break;
        }
        tasks.add(task);
        request.setTasks(tasks);
        updateTask.setRequest(request);
        LOG.warn("更新钉钉待办任务,结束拼装请求,公司id:"+workrecordUpdateTaskDTO.getCorpid());
        try {
            DingtalkWorkrecordHelper.updateWorkrecordTask(updateTask, accessToken);
            return true;
        } catch (Exception e) {
            LOG.error("DingtalkWorkrecordMessageImpl.updateWorkrecordTask 更新单个任务 失败：", e);
        }
        return false;
    }

    /**
     * 批量取消任务
     * @param workrecordUpdateTaskDTO
     * @return
     * @throws
     * @author xingxing.xiao
     * @date 2019/08/05 08:56
     */
    @Override
    public boolean cancelWorkrecordTaskgroup(WorkrecordUpdateTaskDTO workrecordUpdateTaskDTO) {
        String corpid = workrecordUpdateTaskDTO.getCorpid();
        String accessToken;
        String agentId;
        try {
            accessToken = authHelper.getAccessToken(corpid);
            agentId = authHelper.getAgentId(corpid, Env.DING_XBB_APP_ID);
        } catch (Exception e) {
            LOG.error("获取accessToken或agentId失败", e);
            return false;
        }

        String dingtalkWorkrecordActivityId = workrecordUpdateTaskDTO.getDingtalkActivityId();
        String dingtalkProcessInstanceId = workrecordUpdateTaskDTO.getDingtalkInstanceId();

        CancelTask cancelTask = new CancelTask();
        CancelTaskRequest request = new CancelTaskRequest();
        request.setAgentid(Long.valueOf(agentId));
        request.setActivity_id(dingtalkWorkrecordActivityId);
        request.setProcess_instance_id(dingtalkProcessInstanceId);
        cancelTask.setRequest(request);

        try {
            DingtalkWorkrecordHelper.BaseResponse baseResponse = DingtalkWorkrecordHelper.cancelWorkrecordTaskgroup(cancelTask, accessToken);
            if (Objects.equals(baseResponse.getErrcode(), 0L)) {
                return true;
            }
        } catch (Exception e) {
            LOG.error("DingtalkWorkrecordMessageImpl.cancelWorkrecordTaskgroup 批量取消任务 失败：", e);
        }
        return false;
    }

    /**
     * 删除钉钉模板
     * @param corpid
     * @param processCode
     * @author xingxing.xiao
     * @date 2019/11/06 15:22
     */
    @Override
    public boolean delPorcessTemplate(String corpid, String processCode) {
        String accessToken;
        String agentId;
        try {
            accessToken = authHelper.getAccessToken(corpid);
            agentId = authHelper.getAgentId(corpid, Env.DING_XBB_APP_ID);
        } catch (Exception e) {
            LOG.error("获取accessToken或agentId失败", e);
            return false;
        }

        DeleteProcess process = new DeleteProcess();
        DeleteProcessRequest request = new DeleteProcessRequest();
        request.setAgentid(Long.valueOf(agentId));
        request.setProcess_code(processCode);
        process.setRequest(request);
        try {
            DingtalkWorkrecordHelper.BaseResponse baseResponse = DingtalkWorkrecordHelper.deleteWorkrecordTemplate(process, accessToken);
            if (Objects.equals(baseResponse.getErrcode(), 0L)) {
                return true;
            }
        } catch (Exception e) {
            LOG.error("DingtalkWorkrecordMessageImpl.deleteWorkrecordTemplate 删除钉钉模板 失败：", e);
        }
        return false;
    }

    /**
     * 拼接跳转链接
     * eg. http://localhost:8016/index.html?corpid=1&appid=1000&dd_nav_bgcolor=ffff943e#/process/workDetail?processTaskId=935&processNodeTaskId=12104&appId=2035&menuId=7124&formId=6452&saasMark=1&businessType=802&processType=todo
     * @param corpid
     * @param options
     * @return
     */
    public String formatDingtalkLinkUrl(String corpid, PushRefTypePojo.Options options) {
        String linkUrl = proBaseConfig.getPushFrontUrl() + "index.html?corpid=" + corpid + "&appid=" + Env.DING_XBB_APP_ID + "&dd_nav_bgcolor=ffff943e#";
        linkUrl += String.format(DingtalkPageUrlEnum.APPROVAL_DETAIL.getUrl(), options.getProcessTaskId(), options.getProcessNodeTaskId(), options.getAppId(), options.getMenuId(), options.getFormId(), options.getSaasMark(), options.getBusinessType(), options.getProcessType());
        // 钉钉审批标识
        linkUrl += "&fromDingtalk=true";
        return linkUrl;
    }

    /**
     * 删除单个公司es所有的数据(搬的鲁江的代码)
     */
    @Override
    public PaasFormDataEsInitVO deleteAllData(PaasFormDataEsInitDTO paasFormDataEsInitDTO) throws XbbException {
        PaasFormDataEsInitVO dataInitVO = new PaasFormDataEsInitVO();
        try {
            for (IndexTypeEnum indexTypeEnum : IndexTypeEnum.getAllEnum()) {
                try {
                    deleteByQueryCorpid(indexTypeEnum,paasFormDataEsInitDTO.getCorpid());
                } catch (Exception e) {
                    LOG.error("删除失败的索引================"+indexTypeEnum,e);
                    //TODO 已存在则跳过
                    e.printStackTrace();
                }
            }
        } catch (Exception e) {
            throw  new XbbException(BiErrorCodeEnum.API_ERROR_241011);
        }
        return dataInitVO;
    }

    /**
     * 删除单个公司es所有的数据(搬的鲁江的代码)
     */
    @Deprecated
    private void deleteByQueryCorpid(IndexTypeEnum indexTypeEnum,String corpid)   {
        //TODO  2019年7月1日17:34:57    是否要做scrooll
        HttpEntity httpEntity = null;
        try {
            httpEntity = new NStringEntity("{\"query\":{\"bool\":{\"filter\":[{\"term\":{\"corpid.keyword\":\"" +
                    corpid +
                    "\"}}]}}}", ContentType.APPLICATION_JSON);
            String index = indexTypeEnum.getIndex();
            //TODO
            Request request = new Request("POST",index + "/_delete_by_query");
            request.setEntity(httpEntity);
            xbbElasticsearchRestTemplate.getRestClient(index).performRequest(request);
        } catch (Exception e) {
            LOG.error("",e);
        } finally {
            if (Objects.nonNull(httpEntity)) {
                try {
                    ((NStringEntity) httpEntity).close();
                } catch (Exception e) {
                    LOG.error("dataWarehouse.deleteByQuery",e);
                }
            }
        }
    }
}
